package com.hgw.springsecurityjwtdemo02.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hgw.springsecurityjwtdemo02.domian.LoginUser;
import com.hgw.springsecurityjwtdemo02.domian.User;
import com.hgw.springsecurityjwtdemo02.mapper.MenuMapper;
import com.hgw.springsecurityjwtdemo02.mapper.UserMapper;
import com.hgw.springsecurityjwtdemo02.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * Description:
 * Data time:2022/9/1 12:12
 * Author:TQ-3038-HuangGongWei
 */
@Service
public class UserServiceImpl implements UserService, UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .lambda()
                .eq(User::getUserName, userName);
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)) {
            // 如果没有查询到用户则抛出异常
            throw new RuntimeException("用户名或者密码错误！");
        }
        // TODO 查询对应的权限信息
        List<String> perms = menuMapper.selectPermsByUserId(user.getId());
        // 把数据封装成 UserDetails 返回
        return new LoginUser(user,perms);
    }

}
